<template>
  <px-dialog v-model="visible" title="整改" @close="cancel">
    <div class="title">发起整改</div>
    <div class="info-line">
      <div class="label">问题说明</div>
      <div class="content">{{ initiateData.questionState }}</div>
    </div>
    <div class="info-line two">
      <div class="label">整改要求</div>
      <div class="content">{{ initiateData.opinion }}</div>
    </div>
    <div class="title">整改</div>
    <px-form ref="reformingFormRef" :model="reformingFormParams" :rules="reformingFormRules" label-width="100px">
      <px-form-item label="整改结果" prop="result">
        <px-input v-model="reformingFormParams.result" type="textarea" :rows="5" maxlength="300" show-word-limit clearable />
      </px-form-item>
      <px-form-item label="上传照片" prop="pic">
        <PhotoUpload
          photoType="add"
          :photoData="{
            fileType: 'P',
            id: rowData.id
          }"
          :photoList="reformingFormParams.pic"
          :countLimit="20"
          @changePhotoList="onChange"
        />
      </px-form-item>
      <px-form-item label="附件" prop="file">
        <!-- <px-button type="primary" plain @click="handleUpload">上传附件</px-button>
        <span v-if="reformingFormParams.file">{{ reformingFormParams.file?.name }}</span> -->
        <FileUploadComponents
          fileType="add"
          :fileData="{ moduleName: 'eqp' }"
          :fileSize="fileSize"
          :fileList="fileList"
          :multiple="multiple"
          :countLimit="20"
          fileBtnText="上传文件"
          tipText="文件"
          @changeFileList="changeFileList"
        />
      </px-form-item>
      <px-form-item label="审核人" prop="person">
        <px-select v-model="reformingFormParams.person" filterable clearable placeholder="请选择审核人">
          <px-option v-for="item in personList" :key="item.value" :label="item.label" :value="item.label" />
        </px-select>
      </px-form-item>
    </px-form>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancel">取消</px-button>
        <px-button type="primary" @click="saveReforming">确定</px-button>
      </span>
    </template>
  </px-dialog>

  <!-- 上传文件 -->
  <div v-if="fileUploadVisible">
    <FileUpload ref="uploadRef" v-model:visible="fileUploadVisible" :rowData="rowData" @uploadAction="fileUploadConfirm" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, toRefs } from "vue";
import { getPersonListAPI } from "@/api/knowledge/documentManage";
import { saveReformingAPI, uploadFileAPI, getEventLineAPI } from "@/api/energy/monitor";
import { PxMessage } from "px-ui";
import FileUpload from "./fileUpload.vue";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import FileUploadComponents from "@/components/Upload/FileUpload.vue";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => {}
  }
});
const emits = defineEmits(["update:visible", "refresh"]);

const reformingFormRef = ref(null);

const state = reactive({
  reformingFormParams: {
    result: "",
    pic: [],
    images: [],
    file: "",
    person: ""
  },
  fileUploadVisible: false,
  personList: [],
  initiateData: {
    indicator: "",
    ask: ""
  }
});
const { reformingFormParams, fileUploadVisible, personList, initiateData } = toRefs(state);

const reformingFormRules = computed(() => ({
  result: [{ required: true, message: "整改结果不能为空", trigger: "blur" }],
  person: [{ required: true, message: "审核人不能为空", trigger: "change" }]
}));
const fileList = ref([]);
const fileUploadList = ref([]);
const fileSize = ref(20);
const multiple = ref(true);
const countLimit = ref(20);

onMounted(() => {
  getEventLine();
  getPersonList();
});
const changeFileList = val => {
  fileUploadList.value = val.map(item => {
    return {
      // id: item.id,
      // originalName: item.originalName,
      // fileName: item.id,
      // fileType: item.fileType,
      // fileUrl: item.fileUrl,
      // accountId: item.accountId,
      // accountName: item.accountName,
      // status: item.status,
      // createTime: item.createTime,
      // updateTime: item.updateTime,
      alarmId: props.rowData.id,
      name: item.originalName,
      fileKey: item.fileUrl,
      fileSize: item.fileSize,
      fileType: "A",
      extension: item.fileType
    };
  });
};
const onChange = val => {
  state.reformingFormParams.images = val
    .map(item => {
      const data = item?.response?.data;
      return data
        ? {
            alarmId: props.rowData.id,
            name: data.originalName,
            fileKey: data.fileUrl,
            fileSize: data.fileSize,
            fileType: "P",
            extension: data.fileType
          }
        : null;
    })
    .filter(item => !!item);
};
const getEventLine = async () => {
  const params = {
    id: props.rowData.id
  };

  const res = await getEventLineAPI(params);
  let data = res.timeline;
  // 发起整改数据
  let sData = data.filter(item => item.eventType === "S")[0];
  state.initiateData = sData;
};
const getPersonList = async () => {
  state.personList = await getPersonListAPI();
  state.personList.forEach(item => {
    item.id = item.userId;
    item.label = `${item.userId}-${item.username}-${item.realName}`;
    item.value = item.userId;
  });
};
const handleUpload = () => {
  state.fileUploadVisible = true;
};

const fileUploadConfirm = async fileList => {
  let formData = new FormData();
  formData.append("id", props.rowData.id);
  formData.append("eventType", props.rowData.eventType);
  formData.append("fileType", "A");
  formData.append("file", fileList[0].raw);
  const data = await uploadFileAPI(formData);
  state.reformingFormParams.file = {
    alarmId: props.rowData.id,
    name: data.originalName,
    fileKey: data.fileUrl,
    fileSize: data.fileSize,
    fileType: "A",
    extension: data.fileType
  };
  state.fileUploadVisible = false;
  PxMessage.success("上传成功");
};

const saveReforming = () => {
  reformingFormRef.value.validate(async validate => {
    if (validate) {
      // const { result, file, images, person } = state.reformingFormParams;
      const { result, images, person } = state.reformingFormParams;
      const arr = person.split("-");
      const handlerName = arr[arr.length - 1];
      const params = {
        id: props.rowData.id,
        opinion: result,
        handlerId: person,
        handlerName,
        images: images,
        // files: file ? [file] : undefined,
        files: fileUploadList.value ? fileUploadList.value : undefined
      };
      await saveReformingAPI(params);
      emits("refresh");
      PxMessage.success("整改成功");
      emits("update:visible", false);
    }
  });
};

const visible = computed({
  get: () => props.visible,
  set: val => emits("update:visible", val)
});

const cancel = () => {
  emits("update:visible", false);
};
</script>

<style lang="scss" scoped>
.title {
  padding: 8px;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: bold;
  color: #000;
  background: #ebf2fe;
  border-radius: 4px;
}

.info-line {
  display: flex;
  font-size: 14px;
  color: #000;
  border: 1px solid #dfdfdf;

  .label {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    min-width: 100px;
    padding: 8px 11px;
    font-weight: 500;
    background: #ebf2fe;
    border-right: 1px solid #dfdfdf;
  }

  .content {
    width: calc(100% - 100px);
    height: 100%;
    padding: 8px 11px;
    font-weight: 400;
    word-wrap: break-word;
  }
}

.two {
  margin-bottom: 26px;
  border-top: none;
}
</style>
